package com.quectel.cms.controller.partybuildingtask;


import com.quectel.cms.controller.BaseController;
import com.quectel.cms.util.SessionHolder;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.partybuilding.dto.PartyPersonDto;
import com.quectel.core.module.partybuilding.dto.PartyPersonResp;
import com.quectel.core.module.partybuilding.service.PartyPersonService;
import com.quectel.core.module.partybuildingtask.dto.PartyBuildingPlanDto;
import com.quectel.core.module.partybuildingtask.dto.PartyBuildingPlanPersonBindingDto;
import com.quectel.core.module.partybuildingtask.service.PartyBuildingPlanPersonBindingService;
import com.quectel.core.module.partybuildingtask.service.PartyBuildingPlanService;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/05/24 11:32
 */
@RestController
@RequestMapping("partyBuildingPlan")
@Tag(name = "PartyBuildingPlanController", description = "党建任务计划相关api")
public class PartyBuildingPlanController extends BaseController {

    @DubboReference
    private PartyBuildingPlanService partyBuildingPlanService;
    @DubboReference
    private PartyBuildingPlanPersonBindingService partyBuildingPlanPersonBindingService;
    @DubboReference
    private PartyPersonService partyPersonService;
    /**
     * 提前结束党建任务计划
     *
     * @param id
     * @return
     */
    @PostMapping("terminate")
    @RequirePermissions(values = "partyBuildingPlan:edit")
    @Operation(summary = "提前结束党建任务计划")
    public Response<Object> terminate(@RequestBody Long id) {
        //查询是否存在
        PartyBuildingPlanDto partyBuildingPlanDto = partyBuildingPlanService.selectById(id);
        if(partyBuildingPlanDto==null){
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //覆盖结束时间
        partyBuildingPlanService.terminate(partyBuildingPlanDto.getId());

        return Response.ok();
    }

    /**
     * 取消党建任务计划
     *
     * @param id
     * @return
     */
    @PostMapping("cancel")
    @RequirePermissions(values = "partyBuildingPlan:edit")
    @Operation(summary = "取消党建任务计划")
    public Response<Object> cancel(@RequestBody Long id) {
        //查询是否存在
        PartyBuildingPlanDto partyBuildingPlanDto = partyBuildingPlanService.selectById(id);
        if(partyBuildingPlanDto==null){
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        //已经取消不用取消
        if(SystemConstants.YES.equals(partyBuildingPlanDto.getCancel())){
            return  Response.error("已经取消，无须再次取消");
        }

        partyBuildingPlanService.cancel(partyBuildingPlanDto.getId());

        return Response.ok();
    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "partyBuildingPlan:list")
    @Operation(summary = "分页获取党建任务计划列表")
    public Response<Page<PartyBuildingPlanDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = partyBuildingPlanService.queryTotal(request.getParams());

        List<PartyBuildingPlanDto> list = null;
        if (total > 0) {
            list = partyBuildingPlanService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<PartyBuildingPlanDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<PartyBuildingPlanDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "partyBuildingPlan:edit")
    @Operation(summary = "在编辑时根据id查询党建任务计划详情")
    public Response<PartyBuildingPlanDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (partyBuildingPlanService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        PartyBuildingPlanDto partyBuildingPlanDto = partyBuildingPlanService.selectById(id);
        if(partyBuildingPlanDto!=null){
            //查询全部参与人员
            List<PartyBuildingPlanPersonBindingDto> bindingDtos = partyBuildingPlanPersonBindingService.selectByPlanId(id);
            //填充人员信息
            if(CollectionUtils.isNotEmpty(bindingDtos)){
                bindingDtos.forEach(bindingDto -> {
                    PartyPersonDto partyPersonDto = partyPersonService.selectCacheById(bindingDto.getPersonId());
                    //返回部分党员信息
                    PartyPersonResp result = new PartyPersonResp();
                    result.setName(partyPersonDto.getName());
                    result.setMobile(partyPersonDto.getMobile());
                    result.setPartyName(partyPersonDto.getPartyName());
                    bindingDto.setPartyPerson(result);
                });
            }
            partyBuildingPlanDto.setBindPerson(bindingDtos);
        }

        return Response.<PartyBuildingPlanDto>ok().wrap(partyBuildingPlanDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "partyBuildingPlan:info")
    @Operation(summary = "根据id查询党建任务计划的详情")
    public Response<PartyBuildingPlanDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (partyBuildingPlanService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        PartyBuildingPlanDto partyBuildingPlanDto = partyBuildingPlanService.selectById(id);

        if(partyBuildingPlanDto!=null){
            //查询全部参与人员
            List<PartyBuildingPlanPersonBindingDto> bindingDtos = partyBuildingPlanPersonBindingService.selectByPlanId(id);
            //填充人员信息
            if(CollectionUtils.isNotEmpty(bindingDtos)){
                bindingDtos.forEach(bindingDto -> {
                    PartyPersonDto partyPersonDto = partyPersonService.selectCacheById(bindingDto.getPersonId());
                    //返回部分党员信息
                    PartyPersonResp result = new PartyPersonResp();
                    result.setName(partyPersonDto.getName());
                    result.setMobile(partyPersonDto.getMobile());
                    result.setPartyName(partyPersonDto.getPartyName());
                    bindingDto.setPartyPerson(result);
                });
            }
            partyBuildingPlanDto.setBindPerson(bindingDtos);
        }

        return Response.<PartyBuildingPlanDto>ok().wrap(partyBuildingPlanDto);
    }

    /**
     * 保存
     *
     * @param partyBuildingPlanDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "partyBuildingPlan:edit")
    @Operation(summary = "新增党建任务计划")
    public Response<Object> save(@RequestBody @Validated PartyBuildingPlanDto partyBuildingPlanDto) {

        //填充基础数据
        fillSaveCommonData(partyBuildingPlanDto);

        //党组织Id
        partyBuildingPlanDto.setPartyId(SessionHolder.getSysUser().getPartyId());
        partyBuildingPlanDto.setCancel(SystemConstants.NO);

        partyBuildingPlanService.saveOrUpdate(partyBuildingPlanDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param partyBuildingPlanDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "partyBuildingPlan:edit")
    @Operation(summary = "根据id修改党建任务计划")
    public Response<Object> update(@RequestBody  @Validated PartyBuildingPlanDto partyBuildingPlanDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(partyBuildingPlanDto.getId()));
        if (partyBuildingPlanService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(partyBuildingPlanDto);

        partyBuildingPlanService.saveOrUpdate(partyBuildingPlanDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "partyBuildingPlan:delete")
    @Operation(summary = "根据多条记录id批量删除党建任务计划")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (partyBuildingPlanService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        partyBuildingPlanService.deleteBatch(ids);

        return Response.ok();
    }
}
